<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var generateMatrix = function (n) {
        if (n == 1) return [[1]]
        //每一次只输出边界-1
        let res = new Array(n)
        for (let i = 0; i < res.length; i++) {
          res[i] = new Array(n).fill(0)
        }
        //定义循环次数
        let loop = parseInt(n / 2)
        //定义每次循环开始下标
        let startX = 0
        let startY = 0
        //定义边界缩小值，每次都是缩1
        let offset = 1
        //值
        let count = 1
        while (loop--) {
          let i = startX
          let j = startY
          //从左到右
          for (; j < n - offset; j++) {
            res[i][j] = count
            count++
          }
          for (; i < n - offset; i++) {
            res[i][j] = count
            count++
          }
          for (; j > startY; j--) {
            res[i][j] = count++
          }
          for (; i > startX; i--) {
            res[i][j] = count++
          }
          offset++
          startX++
          startY++
          if (n % 2) {
            let middle = parseInt(n / 2)
            res[middle][middle] = count
          }
        }
        return res
      }
      console.log(generateMatrix(4))
    </script>
  </body>
</html>
